#include "lecture.h"

long fsize(FILE * fp)
{
    long pos, size;
    
    pos = ftell(fp);          /* sauver la position courante */
    fseek(fp, 0, SEEK_END);   /* aller en fin */
    size = ftell(fp);         /* lire la taille */
    fseek(fp, pos, SEEK_SET); /* revenir a la position initiale */
    
    return size;
}

bool loadBinaryFile(const char* fileName, ivec * v)
{
  int i, j;
  FILE* file_in = fopen(fileName, "r+b");
  if(file_in == NULL)
    {
      printf("Impossible d'ouvrir le fichier %s", fileName);
      return false;
    }
  
  int file_size = fsize(file_in);
  int nb_samples = file_size*8;

  printf( "file name = %s\nnb_samples = %d samples\n", fileName, nb_samples );

  ivec_set_length(*v, nb_samples);

  char val;
  int size_of_val = (sizeof val) * 8;
  int count = file_size / (sizeof val);

  // Read bit by bit in the file
  for( i = 0; i<count+1; ++i)
    {
      fread (&val,1,sizeof val,file_in);
      for( j = 0 ; j < size_of_val ; j++ )
	  (*v)[i*size_of_val + j] = ((val >> (size_of_val - 1 - j)) & 1);
    }
  
  fclose(file_in);

  return true;
}

bool wavToBinary( const char * filename, ivec v ) {
  int i, j;
  char tmp;

  FILE * F = fopen( filename, "w+b" );
  if(F == NULL)
    {
      printf("Impossible d'ouvrir le fichier %s", filename);
      return false;
    }

  const int size_of_val = (sizeof tmp)*8;
  const int size = ivec_length( v )/size_of_val;

  // Write in the binary file
  for( i = 0 ; i < size ; i++ )
    {
      tmp = (v [ i*size_of_val ]);

      for(j = 1; j<size_of_val; ++j)
	{
	  tmp = (tmp << 1);
          tmp |= (v [ i*size_of_val + j ]);
	}

      fwrite(&tmp, 1, sizeof(tmp), F);
    }

  fclose( F );

  return true;
}
